<template>
  <div class="page-container">
    <button class="back-button" @click="goToHome">
      <span class="icon-arrow-left"></span>
      返回首页
    </button>
    
    <div class="page-header">
      <h1>角色权限管理</h1>
      <p>管理系统角色及对应的权限配置，控制不同用户的系统访问权限</p>
    </div>
    
    <div class="action-bar">
      <button class="add-btn" @click="showAddRoleDialog = true">
        <span class="icon-plus"></span> 新增角色
      </button>
    </div>
    
    <div class="permission-container">
      <div class="roles-list">
        <div 
          class="role-item" 
          v-for="role in roles" 
          :key="role.id"
          :class="{ selected: selectedRoleId === role.id }"
          @click="selectRole(role.id)"
        >
          <div class="role-info">
            <h3>{{ role.name }}</h3>
            <p>{{ role.description || '无描述' }}</p>
            <span class="users-count">{{ role.usersCount }} 名用户</span>
          </div>
          <div class="role-actions">
            <button class="edit-role" @click.stop="editRole(role)">✎</button>
            <button class="delete-role" @click.stop="deleteRole(role.id)">✕</button>
          </div>
        </div>
      </div>
      
      <div class="permission-settings" v-if="selectedRole">
        <div class="permission-header">
          <h2>{{ selectedRole.name }} - 权限配置</h2>
          <button class="save-permission" @click="savePermission">保存权限配置</button>
        </div>
        
        <div class="permission-content">
          <div class="permission-group" v-for="group in permissionGroups" :key="group.id">
            <div class="permission-group-header">
              <label class="group-checkbox">
                <input 
                  type="checkbox" 
                  v-model="group.checked"
                  @change="toggleGroupPermissions(group)"
                >
                <span class="group-name">{{ group.name }}</span>
              </label>
            </div>
            
            <div class="permission-items">
              <div class="permission-item" v-for="perm in group.permissions" :key="perm.id">
                <label>
                  <input 
                    type="checkbox" 
                    v-model="perm.checked"
                    @change="updateGroupCheckStatus(group)"
                  >
                  <span class="permission-name">{{ perm.name }}</span>
                  <span class="permission-desc">{{ perm.description }}</span>
                </label>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <div class="no-role-selected" v-if="!selectedRole">
        请选择一个角色进行权限配置
      </div>
    </div>
    
    <!-- 新增/编辑角色弹窗 -->
    <div class="dialog-mask" v-if="showRoleDialog">
      <div class="dialog-container">
        <div class="dialog-header">
          <h3>{{ isEditRole ? '编辑角色' : '新增角色' }}</h3>
          <button class="close-btn" @click="closeRoleDialog">×</button>
        </div>
        <div class="dialog-body">
          <form class="role-form">
            <div class="form-group">
              <label>角色名称</label>
              <input type="text" v-model="roleForm.name" required>
            </div>
            <div class="form-group">
              <label>角色描述</label>
              <textarea v-model="roleForm.description" rows="3" placeholder="输入角色描述信息"></textarea>
            </div>
          </form>
        </div>
        <div class="dialog-footer">
          <button class="cancel-btn" @click="closeRoleDialog">取消</button>
          <button class="confirm-btn" @click="saveRole">确认</button>
        </div>
      </div>
    </div>
    
    <!-- 保存成功提示 -->
    <div class="toast" v-if="showToast">
      {{ toastMessage }}
    </div>
  </div>
</template>

<script>
export default {
  name: 'RolePermission',
  data() {
    return {
      showAddRoleDialog: false,
      showRoleDialog: false,
      isEditRole: false,
      selectedRoleId: '',
      showToast: false,
      toastMessage: '',
      
      roleForm: {
        id: '',
        name: '',
        description: '',
        usersCount: 0
      },
      
      roles: [
        {
          id: 'admin',
          name: '系统管理员',
          description: '拥有系统所有功能的访问和管理权限',
          usersCount: 2,
          permissions: ['user:manage', 'dept:manage', 'position:manage', 'role:manage', 'order:view', 'order:manage', 'report:view']
        },
        {
          id: 'hr',
          name: '人事专员',
          description: '负责员工和部门管理，无系统配置权限',
          usersCount: 3,
          permissions: ['user:manage', 'dept:manage', 'position:manage', 'order:view']
        },
        {
          id: 'staff',
          name: '普通员工',
          description: '只能查看部分系统信息，无管理权限',
          usersCount: 45,
          permissions: ['order:view']
        }
      ],
      
      permissionGroups: [
        {
          id: 'user',
          name: '用户管理',
          checked: false,
          permissions: [
            { id: 'user:view', name: '查看用户', description: '查看系统用户信息', checked: false },
            { id: 'user:manage', name: '管理用户', description: '新增、编辑、删除用户', checked: false }
          ]
        },
        {
          id: 'dept',
          name: '部门管理',
          checked: false,
          permissions: [
            { id: 'dept:view', name: '查看部门', description: '查看部门信息', checked: false },
            { id: 'dept:manage', name: '管理部门', description: '新增、编辑、删除部门', checked: false }
          ]
        },
        {
          id: 'position',
          name: '岗位管理',
          checked: false,
          permissions: [
            { id: 'position:view', name: '查看岗位', description: '查看岗位信息', checked: false },
            { id: 'position:manage', name: '管理岗位', description: '新增、编辑、删除岗位', checked: false }
          ]
        },
        {
          id: 'role',
          name: '角色权限',
          checked: false,
          permissions: [
            { id: 'role:view', name: '查看角色', description: '查看角色信息', checked: false },
            { id: 'role:manage', name: '管理角色', description: '新增、编辑、删除角色和权限', checked: false }
          ]
        },
        {
          id: 'order',
          name: '工单管理',
          checked: false,
          permissions: [
            { id: 'order:view', name: '查看工单', description: '查看工单信息', checked: false },
            { id: 'order:manage', name: '管理工单', description: '创建、编辑、处理工单', checked: false }
          ]
        },
        {
          id: 'report',
          name: '报表统计',
          checked: false,
          permissions: [
            { id: 'report:view', name: '查看报表', description: '查看统计报表', checked: false },
            { id: 'report:export', name: '导出报表', description: '导出统计报表数据', checked: false }
          ]
        }
      ]
    };
  },
  computed: {
    selectedRole() {
      return this.roles.find(role => role.id === this.selectedRoleId) || null;
    }
  },
  methods: {
    goToHome() {
      this.$router.push('/home');
    },
    selectRole(roleId) {
      this.selectedRoleId = roleId;
      this.loadRolePermissions();
    },
    loadRolePermissions() {
      if (!this.selectedRole) return;
      
      // 重置所有权限勾选状态
      this.permissionGroups.forEach(group => {
        group.permissions.forEach(perm => {
          perm.checked = this.selectedRole.permissions.includes(perm.id);
        });
        this.updateGroupCheckStatus(group);
      });
    },
    toggleGroupPermissions(group) {
      group.permissions.forEach(perm => {
        perm.checked = group.checked;
      });
    },
    updateGroupCheckStatus(group) {
      const allChecked = group.permissions.every(perm => perm.checked);
      const noneChecked = group.permissions.every(perm => !perm.checked);
      group.checked = allChecked;
      // 处理半选状态的视觉反馈（通过CSS实现）
      group.indeterminate = !allChecked && !noneChecked;
    },
    savePermission() {
      if (!this.selectedRole) return;
      
      // 收集所有勾选的权限
      const selectedPermissions = [];
      this.permissionGroups.forEach(group => {
        group.permissions.forEach(perm => {
          if (perm.checked) {
            selectedPermissions.push(perm.id);
          }
        });
      });
      
      // 更新角色权限
      const roleIndex = this.roles.findIndex(r => r.id === this.selectedRoleId);
      if (roleIndex !== -1) {
        this.roles[roleIndex].permissions = selectedPermissions;
      }
      
      // 显示成功提示
      this.showToastMessage('权限配置已保存');
    },
    editRole(role) {
      this.roleForm = { ...role };
      this.isEditRole = true;
      this.showRoleDialog = true;
    },
    deleteRole(roleId) {
      if (roleId === 'admin') {
        this.showToastMessage('系统管理员角色不能删除', 'error');
        return;
      }
      
      if (confirm('确定要删除该角色吗？')) {
        this.roles = this.roles.filter(role => role.id !== roleId);
        if (this.selectedRoleId === roleId) {
          this.selectedRoleId = '';
        }
        this.showToastMessage('角色已删除');
      }
    },
    closeRoleDialog() {
      this.showRoleDialog = false;
      this.showAddRoleDialog = false;
      this.isEditRole = false;
      this.roleForm = {
        id: '',
        name: '',
        description: '',
        usersCount: 0
      };
    },
    saveRole() {
      if (!this.roleForm.name.trim()) {
        this.showToastMessage('角色名称不能为空', 'error');
        return;
      }
      
      if (this.isEditRole) {
        // 编辑角色
        const roleIndex = this.roles.findIndex(r => r.id === this.roleForm.id);
        if (roleIndex !== -1) {
          this.roles[roleIndex] = { ...this.roles[roleIndex], ...this.roleForm };
        }
        this.showToastMessage('角色已更新');
      } else {
        // 新增角色
        const newRole = {
          ...this.roleForm,
          id: 'role_' + Date.now().toString().slice(-6),
          usersCount: 0,
          permissions: []
        };
        this.roles.push(newRole);
        this.showToastMessage('角色已创建');
      }
      
      this.closeRoleDialog();
    },
    showToastMessage(message, type = 'success') {
      this.toastType = type;
      this.toastMessage = message;
      this.showToast = true;
      
      setTimeout(() => {
        this.showToast = false;
      }, 3000);
    }
  },
  watch: {
    showAddRoleDialog(newVal) {
      if (newVal) {
        this.roleForm = {
          id: '',
          name: '',
          description: '',
          usersCount: 0
        };
        this.isEditRole = false;
        this.showRoleDialog = true;
      }
    }
  }
};
</script>

<style scoped>
.page-container {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

.page-header {
  margin: 20px 0 30px;
}

.page-header h1 {
  color: #2c3e50;
  margin-bottom: 10px;
  font-size: 24px;
}

.page-header p {
  color: #7f8c8d;
  font-size: 14px;
  margin: 0;
}

.action-bar {
  margin-bottom: 30px;
}

.add-btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s;
  background-color: #2ecc71;
  color: white;
  display: flex;
  align-items: center;
  gap: 6px;
}

.add-btn:hover {
  background-color: #27ae60;
}

.permission-container {
  display: grid;
  grid-template-columns: 300px 1fr;
  gap: 30px;
}

.roles-list {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.08);
  padding: 10px;
  max-height: 600px;
  overflow-y: auto;
}

.role-item {
  padding: 15px;
  border-radius: 6px;
  margin-bottom: 10px;
  cursor: pointer;
  transition: all 0.2s;
  border: 1px solid transparent;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.role-item:hover {
  background-color: #f8f9fa;
  border-color: #e1e4e8;
}

.role-item.selected {
  background-color: #e6f7ff;
  border-color: #91d5ff;
}

.role-info h3 {
  margin: 0 0 5px 0;
  color: #2c3e50;
  font-size: 16px;
}

.role-info p {
  margin: 0 0 8px 0;
  color: #7f8c8d;
  font-size: 13px;
  line-height: 1.4;
}

.users-count {
  font-size: 12px;
  color: #3498db;
  background-color: rgba(52, 152, 219, 0.1);
  padding: 2px 6px;
  border-radius: 10px;
}

.role-actions {
  display: flex;
  gap: 5px;
}

.edit-role, .delete-role {
  background: none;
  border: none;
  width: 24px;
  height: 24px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s;
  opacity: 0.7;
}

.role-item:hover .edit-role,
.role-item:hover .delete-role {
  opacity: 1;
}

.edit-role {
  color: #3498db;
}

.edit-role:hover {
  background-color: rgba(52, 152, 219, 0.1);
}

.delete-role {
  color: #e74c3c;
}

.delete-role:hover {
  background-color: rgba(231, 76, 60, 0.1);
}

.permission-settings {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.08);
  padding: 20px;
  max-height: 600px;
  overflow-y: auto;
}

.permission-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 25px;
  padding-bottom: 15px;
  border-bottom: 1px solid #f1f1f1;
}

.permission-header h2 {
  margin: 0;
  color: #2c3e50;
  font-size: 18px;
}

.save-permission {
  padding: 8px 16px;
  background-color: #3498db;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s;
  font-size: 14px;
}

.save-permission:hover {
  background-color: #2980b9;
}

.permission-group {
  margin-bottom: 20px;
  border: 1px solid #f1f1f1;
  border-radius: 6px;
  overflow: hidden;
}

.permission-group-header {
  background-color: #f8f9fa;
  padding: 12px 15px;
  border-bottom: 1px solid #f1f1f1;
}

.group-checkbox {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.group-checkbox input {
  margin-right: 8px;
  width: 16px;
  height: 16px;
}

/* 半选状态样式 */
.group-checkbox input:indeterminate + .group-name::before {
  content: "—";
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  font-size: 14px;
}

.group-name {
  color: #2c3e50;
  font-weight: 500;
  position: relative;
  padding-left: 24px;
}

.group-name::before {
  content: "";
  position: absolute;
  left: 0;
  top: 50%;
  width: 16px;
  height: 16px;
  transform: translateY(-50%);
  border: 1px solid #ccc;
  border-radius: 3px;
  background-color: white;
}

.permission-items {
  padding: 10px 15px;
}

.permission-item {
  padding: 8px 0;
  border-bottom: 1px dashed #f1f1f1;
}

.permission-item:last-child {
  border-bottom: none;
}

.permission-item label {
  display: flex;
  align-items: flex-start;
  cursor: pointer;
}

.permission-item input {
  margin: 3px 10px 0 0;
  width: 16px;
  height: 16px;
}

.permission-name {
  font-weight: 500;
  color: #2c3e50;
  margin-right: 10px;
}

.permission-desc {
  color: #7f8c8d;
  font-size: 13px;
  flex-grow: 1;
}

.no-role-selected {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.08);
  padding: 60px 20px;
  text-align: center;
  color: #7f8c8d;
}

/* 弹窗样式 */
.dialog-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.dialog-container {
  background-color: white;
  border-radius: 6px;
  width: 100%;
  max-width: 500px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
}

.dialog-header {
  padding: 15px 20px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.dialog-header h3 {
  margin: 0;
  color: #2c3e50;
  font-size: 18px;
}

.close-btn {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  color: #7f8c8d;
  transition: color 0.2s;
}

.close-btn:hover {
  color: #e74c3c;
}

.dialog-body {
  padding: 20px;
}

.role-form {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: 500;
  color: #2c3e50;
}

.form-group input, 
.form-group textarea {
  width: 100%;
  padding: 8px 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.form-group textarea {
  resize: vertical;
}

.dialog-footer {
  padding: 15px 20px;
  border-top: 1px solid #eee;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.cancel-btn, .confirm-btn {
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s;
}

.cancel-btn {
  background-color: #f1f1f1;
  border: 1px solid #ddd;
  color: #7f8c8d;
}

.cancel-btn:hover {
  background-color: #e9e9e9;
}

.confirm-btn {
  background-color: #3498db;
  border: 1px solid #3498db;
  color: white;
}

.confirm-btn:hover {
  background-color: #2980b9;
}

/* 提示框样式 */
.toast {
  position: fixed;
  top: 20px;
  right: 20px;
  padding: 10px 20px;
  border-radius: 4px;
  background-color: #2ecc71;
  color: white;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
  z-index: 1001;
  animation: slideIn 0.3s, fadeOut 0.3s 2.7s;
}

.toast.error {
  background-color: #e74c3c;
}

@keyframes slideIn {
  from {
    transform: translateX(100%);
    opacity: 0;
  }
  to {
    transform: translateX(0);
    opacity: 1;
  }
}

@keyframes fadeOut {
  from {
    opacity: 1;
  }
  to {
    opacity: 0;
  }
}

/* 继承并保留原有按钮样式 */
.back-button {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 15px;
  background: #3498db;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  transition: all 0.3s;
  margin-right: 20px;
  font-weight: 500;
}

.back-button:hover {
  background: #2980b9;
  transform: translateY(-2px);
}
</style>